#include <iostream>

#include "book_info.h"
#include "lib_manager.h"
#include "time.h"


// 添加图书信息
bool Library_UpdateManager::AddBookInfo(BookInfo book_info) {
    // 向Books表添加图书信息
    std::string op1 = "INSERT INTO Books (ID,Title,Author,Publisher,PublishDate,Quantity) VALUES ('" + book_info.ID + "', '" +
        book_info.Title + "', '" + book_info.Author + "', '" + book_info.Publisher + "', '" +
        formatTime(book_info.PublishDate) + "', " + std::to_string(book_info.Quantity) + ")";
    db->accept(operater, op1.c_str());

    uint64_t row_count = operater->getUpdateResult();
    return row_count > 0;
}

// 图书采购操作
bool Library_UpdateManager::BookPurchase(PurchaseInfo purchase_info) {

    // 更新图书数量
    if (!UpdateBookQuantity(purchase_info.BookID, purchase_info.Quantity)) {
        return false;
    }


    // 向Purchases表添加采购信息
    std::string op2 = "INSERT INTO Purchases (BookID, Quantity, Date, Price) VALUES ('" +
        purchase_info.BookID + "', " + std::to_string(purchase_info.Quantity) +
        ", '" + formatTime(purchase_info.Date) + "', " + std::to_string(purchase_info.Price) + ")";
    db->accept(operater, op2.c_str());


    uint64_t row_count = operater->getUpdateResult();
    return row_count > 0;
}

// 图书淘汰操作
bool Library_UpdateManager::BookElimination(DiscardInfo discard_info) {

    // 先检查图书数量是否足够
    if (!UpdateBookQuantity(discard_info.BookID, -discard_info.Quantity)) {
        return false;
    }


    // 向Discards表添加淘汰信息
    std::string op = "INSERT INTO Discards (BookID, Quantity, Date) VALUES ('" + discard_info.BookID + "', " + std::to_string(discard_info.Quantity) + ", '" + formatTime(discard_info.Date) + "')";
    db->accept(operater, op.c_str());

    uint64_t row_count = operater->getUpdateResult();

    return row_count > 0;
}

// 图书租借操作
bool Library_UpdateManager::BookRent(BorrowInfo borrow_info) {

    // 一般情况下，借出一本书
    if (!UpdateBookQuantity(borrow_info.BookID, -1)) {
        return false;
    }

    // 向Borrows表添加租借信息
    std::string op = "INSERT INTO Borrows (BookID, UserID, BorrowDate, ReturnDate, Status) VALUES ('" + borrow_info.BookID + "', '" + borrow_info.UserID + "', '" + formatTime(borrow_info.BorrowDate) + "', '" +
        formatTime(borrow_info.ReturnDate) + "', '" + borrow_info.Status + "')";
    db->accept(operater, op.c_str());

    uint64_t row_count = operater->getUpdateResult();

    return row_count > 0;
}

// 图书归还操作
bool Library_UpdateManager::BookReturn(const std::string& borrow_id, time_t return_date) {
    // 查询Borrows表以获取BookID
    std::string query = "SELECT BookID FROM Borrows WHERE BorrowID = '" + borrow_id + "'";
    db->accept(operater, query.c_str());

    if (operater->getQueryResult().second == 0) {
        std::cerr << "Error: Borrow record not found with ID: " << borrow_id << std::endl;
        return false;
    }

    std::vector<std::string> row = operater->getQueryResult().first.rows[0].fields;
    std::string book_id = row[0];

    // 更新Borrows表中的状态和实际归还日期
    std::string update_borrow = "UPDATE Borrows SET Status = '已归还', ReturnDate = '" + formatTime(return_date) + "' WHERE BorrowID = '" + borrow_id + "'";
    db->accept(operater, update_borrow.c_str());

    uint64_t row_count = operater->getUpdateResult();
    if (row_count == 0) {
        std::cerr << "Error: Failed to update borrow record with ID: " << borrow_id << std::endl;
        return false;
    }

    // 更新Books表中的图书数量
    if (!UpdateBookQuantity(book_id, 1)) {
        std::cerr << "Error: Failed to update book quantity for book ID: " << book_id << std::endl;
        return false;
    }

    return true;
}


// 更新图书数量
bool Library_UpdateManager::UpdateBookQuantity(const std::string& book_id, int quantity_change) {
    // 查询当前图书数量
    std::string query = "SELECT Quantity FROM Books WHERE ID = '" + book_id + "'";
    db->accept(operater, query.c_str());

    if (operater->getQueryResult().second == 0) {
        std::cerr << "Error: Book not found with ID: " << book_id << std::endl;
        return false;
    }

    std::vector<std::string> row = operater->getQueryResult().first.rows[0].fields;
    int current_quantity = std::stoi(row[0]);
    int new_quantity = current_quantity + quantity_change;

    if (new_quantity < 0) {
        std::cerr << "Error: Cannot update to a negative quantity." << std::endl;
        return false;
    }

    // 更新图书数量
    std::string update_query = "UPDATE Books SET Quantity = " + std::to_string(new_quantity) + " WHERE ID = '" + book_id + "'";
    db->accept(operater, update_query.c_str());

    uint64_t row_count = operater->getUpdateResult();

    return row_count > 0;
}



// 查询所有图书信息及其库存情况
QueryResult Library_QueryManager::GetBooksInfo() {
    std::string query = "SELECT ID, Title, Author, Publisher, PublishDate, Quantity FROM Books";
    return ExecuteQuery(query);
}

// 查询采购记录
QueryResult Library_QueryManager::GetPurchasesInfo() {
    std::string query = "SELECT PurchaseID, BookID, Quantity, Date, Price FROM Purchases";
    return ExecuteQuery(query);
}

// 查询淘汰记录
QueryResult Library_QueryManager::GetDiscardsInfo() {
    std::string query = "SELECT DiscardID, BookID, Quantity, Date FROM Discards";
    return ExecuteQuery(query);
}

// 查询租借情况
QueryResult Library_QueryManager::GetBorrowsInfo() {
    std::string query = "SELECT BorrowID, BookID, UserID, BorrowDate, ReturnDate, Status FROM Borrows";
    return ExecuteQuery(query);
}



// 执行查询并返回结果
QueryResult Library_QueryManager::ExecuteQuery(const std::string& query) {
    QueryResult result;
    db->accept(operater, query.c_str());

    if (!operater->IsOperationSuccess()) {
        std::cerr << "Error: Failed to execute query: " << query << std::endl;
        return result;
    }

    result = operater->getQueryResult().first;
    return result;
}




// 统计图书采购情况
QueryResult Library_StatisticsManager::GetPurchasesStatistics() {
    std::string query = "SELECT COUNT(*), SUM(Quantity), MIN(Date), MAX(Date) FROM Purchases";
    return ExecuteQuery(query);
}

// 统计图书库存情况
QueryResult Library_StatisticsManager::GetInventoryStatistics() {
    std::string query = "SELECT COUNT(*), SUM(Quantity) FROM Books WHERE Quantity > 0";
    return ExecuteQuery(query);
}

// 统计图书淘汰情况
QueryResult Library_StatisticsManager::GetDiscardsStatistics() {
    std::string query = "SELECT COUNT(*), SUM(Quantity), MIN(Date), MAX(Date) FROM Discards";
    return ExecuteQuery(query);
}

// 统计图书租借情况
QueryResult Library_StatisticsManager::GetBorrowsStatistics() {
    std::string query = "SELECT COUNT(*), SUM(CASE WHEN Status = '已借出' THEN 1 ELSE 0 END) AS Borrowed, "
        "SUM(CASE WHEN Status = '已归还' THEN 1 ELSE 0 END) AS Returned, "
        "SUM(CASE WHEN Status = '逾期未还' THEN 1 ELSE 0 END) AS Overdue "
        "FROM Borrows";
    return ExecuteQuery(query);
}

// 执行查询并返回结果
QueryResult Library_StatisticsManager::ExecuteQuery(const std::string& query) {
    QueryResult result;
    db->accept(operater, query.c_str());

    if (!operater->IsOperationSuccess()) {
        std::cerr << "Error: Failed to execute query: " << query << std::endl;
        return result;
    }

    result = operater->getQueryResult().first;
    return result;
}